from django.shortcuts import render_to_response
from films import  setttings
import os
import urllib.parse
# Create your views here.

class Item :

    def __init__(self , path ):
        self.isdir = False if os.path.isfile(path) else True
        parent , name = os.path.split(path)
        self.parent = parent
        self.name = self.__remove_tail__(name)
        self.path = path

    def __remove_tail__(self,name):
        if '.' not in name : return name
        items = name.split('.')[:-1]
        return '.'.join(items)

    def __repr__(self):
        return "(%s : %s %s)"%(self.parent ,self.name , self.isdir)

    def url(self):
        print(self.path)
        path = self.path.lstrip(setttings.FILM_SEARCH_HOME)
        if not path.startswith('/') and not path.startswith('\\'):
            path = '/' + path
        print(path)
        path = setttings.URL_PRFFIX + path
        path = path.replace( os.path.sep , '/')
        print('item url',path)
        return path

    def parenturl(self):
        parent = self.parent.strip(setttings.FILM_SEARCH_HOME)
        if not parent.startswith('/') and\
                not parent.startswith('\\'):
            parent = '/' + parent
        print('aa' , parent)
        parent =  setttings.URL_PRFFIX + parent
        print('bb' , parent)
        parent.replace( os.path.sep , '/' )
        return parent


def filting_itmes(items , exp=None):
    if items is None :return  None
    items_dict = {  }
    for item in items :
        if item.parent not in items_dict :
            items_dict[item.parent] = []
        items_dict[item.parent].append(item)

    filted_items = []
    for p in items_dict.keys() :
        items_of_same_parent = items_dict[p]
        if len(items_of_same_parent) == 1  :
            filted_items.append(items_of_same_parent[0])
        elif exp is not None and p == exp :
            filted_items.extend( items_of_same_parent )
        else :
            filted_items.append(Item(p))
    return filted_items

def listdir( path ) :
    dir = path
    if not os.path.exists(dir) or os.path.isfile(dir) :
        return
    parent , name = os.path.split(path)
    if name.startswith('.') or name.startswith('$') :
        return

    items = [ os.path.join(dir , d) for d in os.listdir(dir) ]
    dirs = [ os.path.join(dir , d) for d in items if os.path.isdir(d) ]
    videos = [ os.path.join(dir,f) for f in items if os.path.isfile(f) and f.endswith('.mp4') ]
    videos = [ Item(v) for v in videos ]
    for d in dirs :
        items = listdir(d)
        if items is not None : videos.extend(items)
    return videos

def itemsheader(path):
    dir = os.path.join( setttings.FILM_SEARCH_HOME , path )
    if os.path.abspath(dir) == os.path.abspath(setttings.FILM_SEARCH_HOME) :
        return 'Home'
    parent , name = os.path.split(dir)
    return name

def index(request):

    search_dir = request.GET.get('path' , setttings.URL_PRFFIX).lstrip(setttings.URL_PRFFIX)
    search_dir = os.path.join(setttings.FILM_SEARCH_HOME , search_dir )
    items = listdir( search_dir )
    header = itemsheader( search_dir )
    video = request.GET.get('video' , '' )
    items = filting_itmes(items , exp=search_dir)

    return render_to_response("index.html" , {
        'items' : items ,
        'header' : header ,
        'video' : video
    })